var Report = function(cfg) {
	var me = this;
	cfg.params = cfg.params || {};
	this.getWhere = function() {
		var values = me.form.getForm().getValues();
		var where = [];
		for (var field in values) {
			var value = values[field];
			if (!value) {
				continue;
			}
			var ctrl = me.form.getForm().findField(field);
			if (ctrl instanceof Ext.form.DateField) {// 日期控件
				var temp = field.split('@');
				if (temp.length == 2 && temp[1] == 'start') {
					where.push(" and " + temp[0] + " >='" + value + "'");
				} else if (temp.length == 2 && temp[1] == 'end') {
					where.push(" and " + temp[0] + " <='" + value + "'");
				} else {
					where.push(" and " + field + " ='" + value + "'");
				}
			} else if (ctrl instanceof Ext.ux.SuperComboTree) {// 字典控件
				if (ctrl.multi) {
					where.push(" and " + field + " in('"
							+ (value.replace(/,/g, "','")) + "')");
				} else {
					where.push(" and " + field + "='" + value + "'");
				}
			} else if (ctrl instanceof Ext.form.NumberField) {
				where.push(" and " + field + "='" + value + "'");
			} else if (ctrl instanceof Ext.form.ComboBox) {
				if (ctrl.multi) {
					where.push(" and " + field + " in('"
							+ (value.replace(/,/g, "','")) + "')");
				} else {
					where.push(" and " + field + "='" + value + "'");
				}
			} else {
				where.push(" and " + field + " like q'<%" + value + "%>'");
			}
		}
		return where.join("");
	};

	/**
	 * 查询
	 */
	this.search = function() {
		var where = me.getWhere();
		me.grid.getStore().baseParams['where'] = where;
		me.grid.getStore().load();
	};

	this.showDetails = function(grid, i) {
		var rec = grid.getStore().getAt(i);
		var cm = grid.getColumnModel();
		var chr = '';
		for (var i = 1; i < cm.getColumnCount(); i++) {
			chr += '<b style="font-size:18px">' + cm.getColumnHeader(i)
					+ '：</b>';
			chr += rec.get(cm.getDataIndex(i)) + '</br>';
		}
		var win = new Ext.Window({
					title : '详细信息',
					width : 550,
					height : 420,
					modal : true,
					layout : 'fit',
					border : false,
					items : [{
								xtype : 'htmleditor',
								value : chr,
								readOnly : true
							}],
					buttons : [{
								text : '关闭',
								iconCls : 'icon-cancel',
								handler : function() {
									win.close();
								}
							}]
				}).show();
	};

	this.initBar = function() {
		var noQuery = cfg.querys.length == 0;
		var noExcel = !cfg.exceltpl;
		var tools = new Ext.Toolbar({
					style : 'border:0;',
					buttonAlign : 'left',
					items : [{
								text : '查询',
								iconCls : 'icon-search',
								hidden : noQuery,
								handler : function() {
									me.search();
								}
							}, {
								text : noQuery ? '刷新' : '重置',
								iconCls : 'icon-refresh',
								handler : function() {
									// 重置表单
									me.form.getForm().reset();
									me.search();
								}
							}]
				});
		if (!noExcel) {
			tools.addItem('-');
			tools.addItem({// 导出excel
				text : '导出Excel',
				iconCls : 'icon-excel',
				hidden : !cfg.exceltpl,
				handler : function() {
					if (me.grid.getStore().getCount() == 0) {
						My.alert('当前没有数据，不能执行导出!');
						return;
					}
					var form = new Ext.form.FormPanel({
								border : false,
								padding : 5,
								labelWidth : 70,
								standardSubmit : true,
								baseParams : {
									id : cfg.id,
									where : me.grid.getStore().baseParams.where
								},
								url : My.url('/report/export2Excel.htm'),
								items : []
							});
					/**
					 * 导出excel
					 */
					var exportExcel = function() {
						if (!form.getForm().isValid()) {
							My.alert('您输入的页数不对，请检查');
							return;
						}
						if (form.baseParams && !form.paramsAdded) {
							for (i in form.baseParams) {
								form.add({
											xtype : 'hidden',
											name : i,
											value : form.baseParams[i]
										});
							}
							form.doLayout();
							form.paramsAdded = true;
						}
						form.getForm().submit();
					};
					new Ext.Window({
								title : '导出Excel',
								width : 300,
								autoHeight : true,
								modal : true,
								items : [form]
							}).show(false, function(w) {
								exportExcel();
								w.close();
							});
				}
			});
		}
		var height = 27;
		var hidden = false;
		this.bar = new Ext.Panel({
					region : 'north',
					height : height,
					hidden : hidden,
					bodyStyle : 'border-left:0;border-right:0;',
					items : [tools]
				});
	};
	this.initForm = function() {
		// 循环字段，将tab字段查询出来
		var fields = [];
		Ext.each(cfg.querys, function(field) {
					fields.push(field);
				});
		// var height = Math.ceil(fields.length / columns) * 26 + 10;// 计算Form高度
		this.form = new Form({
					region : 'north',
					// height : height,
					autoHeight : true,
					padding : '5px 5px 1px 5px',
					columns : cfg.columns || 2,
					fields : fields,
					labelWidth : 100,
					columnWidth : 406,
					autoScroll : false,
					border : false,
					bodyStyle : 'border-left:0;border-top:0;border-right:0;',
					listeners : {
						afterrender : function(t) {
							new Ext.KeyNav(t.el, {
										"enter" : function(e) {
											me.search();
										}
									});
						}
					}
				});
	};
	this.initGrid = function() {
		var sm = new Ext.grid.RowSelectionModel();
		var fields = [];
		var columns = [new Ext.grid.RowNumberer({
					header : '序号',
					width : 36
				})];
		Ext.each(cfg.cols, function(col) {
					var dataIndex = col.columnname.toLowerCase();
					fields.push(dataIndex);
					// 如果显示
					if (col.display == 1) {
						var column = {
							header : col.chinesename,
							dataIndex : dataIndex,
							width : col.width || 120,
							renderer : function(v, m, r, ri, ci, s) {
								// 自定义渲染方法
								if (col.renderer) {
									// 执行动态脚本
									eval("(function(){" + col.renderer + "})()");
								}
								// 返回值
								return v;
							}
						};
						columns.push(column);
					}
				});
		// 列头分组
		var group = [];
		if (cfg.headergroup) {
			var rows = cfg.headergroup;
			if (rows.length > 0) {
				group = new Ext.ux.grid.ColumnHeaderGroup({
							rows : rows
						});
			}
		}
		var startTime = 0;
		var endTime = 0;
		// Store
		var store = new Ext.data.JsonStore({
					fields : fields,
					proxy : new Ext.data.HttpProxy({
								url : My.url('/report/query.htm'),
								timeout : 360000
							}),
					baseParams : {
						id : cfg.id,
						haspaging : cfg.haspaging,
						start : 0,
						limit : cfg.pagesize
					},
					root : 'data',
					autoLoad : false,
					applySort : function() {
						if (this.sortInfo && !this.remoteSort) {
							var s = this.sortInfo, f = s.field;
							var st = this.fields.get(f).sortType;
							var fn = function(r1, r2) {
								var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
								if (cfg.hastotal == '1') {
									if (r1.get(cfg.showcol) == '合计') {
										return 0;
									}
								}
								// 中文排序不正确解决
								if (typeof(v1) == "string") {
									return v1.localeCompare(v2);
								}
								return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
							};
							this.data.sort(s.direction, fn);
							if (this.snapshot && this.snapshot != this.data) {
								this.snapshot.sort(s.direction, fn);
							}
						}
					},
					listeners : {
						beforeload : function(t) {
							startTime = new Date().getTime();
						},
						exception : function(d, t, a, opts, r, arg) {
							var o = Ext.util.JSON.decode(r.responseText);
							My.error(o.msg);
						},
						load : function(s, rs) {
							try {
								endTime = new Date().getTime();
								var ms = (endTime - startTime);
								var hs = '';
								if (ms < 60000) {
									hs = (Math.round(ms / 1000.0 * 100) / 100)
											+ ' 秒';
								} else {
									hs = (Math.round(ms / 60000.0 * 100) / 100)
											+ ' 分';
								}
								toolbar.getComponent('haoshi').setText(hs);
								var zongshu = toolbar.getComponent('zongshu');
								if (zongshu) {
									zongshu.setText(rs.length);
								}
							} catch (e) {
							}
						}
					}
				});
		var toolbar = new Ext.Toolbar({
					store : store,
					pageSize : 10000,
					displayInfo : true,
					items : ['查询用时：', {
								xtype : 'tbtext',
								itemId : 'haoshi'
							}, '->', '共', {
								xtype : 'tbtext',
								itemId : 'zongshu',
								text : '0'
							}, '条']
				});
		if (cfg.haspaging == '1') {
			toolbar = new Ext.PagingToolbar({
						pageSize : cfg.pagesize,
						store : store,
						displayInfo : true,
						updateInfo : function() {
							if (this.displayItem) {
								var count = this.store.getCount();
								var toCount = this.cursor + count;
								if (cfg.haspaging) {
									toCount -= 1;
								}
								var msg = count == 0 ? this.emptyMsg : String
										.format(this.displayMsg, this.cursor
														+ 1, toCount,
												this.store.getTotalCount());
								this.displayItem.setText(msg);
							}
						},
						items : ['-', '每页显示：', {
							xtype : 'combo',
							twinTrigger : false,
							width : 60,
							triggerAction : 'all',
							mode : 'local',
							editable : false,
							store : [[50, '50'], [100, '100'], [200, '200'],
									[500, '500'], [999999999, '全部']],
							value : cfg.pagesize,
							listeners : {
								select : function(t, r) {
									var v = t.getValue() || 50;
									toolbar.pageSize = v;
									store.baseParams.limit = v;
									store.baseParams.start = 0;
									store.load();
								}
							}
						}, '条，', '查询用时：', {
							xtype : 'tbtext',
							itemId : 'haoshi'
						}]
					});
		}
		this.grid = new Ext.grid.GridPanel({
					region : 'center',
					loadMask : true,
					border : false,
					stripeRows : true,
					columnLines : true,
					enableHdMenu : false,
					plugins : group,
					sm : sm,
					cm : new Ext.grid.ColumnModel({
								defaults : {
									sortable : true,
									align : 'center'
								},
								columns : columns
							}),
					store : store,
					bbar : toolbar,
					listeners : {
						mouseover : function(e) {// 添加mouseover事件
							var t = e.getTarget();
							var index = me.grid.getView().findRowIndex(t);// 根据mouse所在的target可以取到列的位置
							var cell = me.grid.getView().findCellIndex(t);
							var text = Ext.util.Format.trim(t.innerText);// 去掉文字两边的空格
							if (index !== false && cell > 0 && text) {// 当取到了正确的列时，（因为如果传入的target列没有取到的时候会返回false）
								var rowEl = Ext.get(t); // 把target转换成Ext.Element对象
								rowEl.set({
											'title' : text
										}, false);
							}
						},
						rowdblclick : function(g, i, e) {
							me.showDetails(g, i);
						},
						columnresize : function(i, size) {
							if (Ext.isChrome) {
								me.grid.getView().refresh();
							}
						}
					}
				});
	};
	this.initQuery = function() {
		this.initGrid();
		this.initForm();
		this.initBar();
		this.query = new Ext.Panel({
					border : false,
					layout : 'border',
					items : [this.form, {
								xtype : 'container',
								region : 'center',
								layout : 'border',
								items : [this.bar, this.grid]
							}],
					listeners : {
						afterrender : function() {
							me.query.doLayout();
							// 自动加载
							if (cfg.autoload == '1') {
								setTimeout(function() {
											me.search();
										}, 100);
							}
						}
					}
				});
	};
	this.initQuery();
	return this;
};
// 渲染
Ext.onReady(function() {
			var json = Ext.get('cfg').dom.value;
			var cfg = Ext.decode(json.replace(/&dyh;/g, '\''));
			var report = new Report(cfg);
			new Ext.Viewport({
						layout : 'fit',
						items : [report.query],
						listeners : {
							afterlayout : function() {
							}
						}
					});
		});